<template>
	<el-container>
		<el-aside width="400px">
			<el-container>
				<el-header>
					<div class="tppText">{{ template_name ? template_name : '--' }}</div>
				</el-header>
				<el-main class="nopadding print_box">
					<el-container>
						<el-header style="height: 100px;padding: 0">
							<div style="width: 100%;">
								<el-tabs type="card" v-model="groupId" @tab-change="tabChange">
									<el-tab-pane v-for="(item,index) in tabList" :key='index' :label="item.name" :name="index"></el-tab-pane>
								</el-tabs>
								<el-alert
									title="点击字段插入值（光标所在位置）"
									type="warning"
									:closable="false"
									show-icon
								>
								</el-alert>
							</div>
						</el-header>
						<el-main class="nopadding">
							<el-tree ref="menu" class="menu" node-key="id" :data="menuList" :props="menuProps" :current-node-key="''" draggable highlight-current :expand-on-click-node="false" @node-click="menuClick"></el-tree>
						</el-main>
					</el-container>
				</el-main>
			</el-container>
		</el-aside>
		<el-container>
			<el-header>
				<div class="left-panel"></div>
				<div class="right-panel">
					<div class="right-panel-search">
						<el-button type="success" plain @click="toPrint">打印</el-button>
						<el-button type="success" plain @click="preview">预览</el-button>
						<el-button type="primary" @click="submit">保存</el-button>
						<el-button @click="close">返回</el-button>
					</div>
				</div>
			</el-header>
			<el-main>
				<sc-editor-print
					ref="editor"
					v-model="form.content"
					placeholder="请输入"
					@getTable="getTable"
					@changeHtml ='changeHtml'
				></sc-editor-print>
			</el-main>
		</el-container>
	</el-container>
</template>
<script>
import tinymcePrint from 'tinymce/tinymce'
import store from "@/store";
import $ from "jquery"
import useTabs from '@/utils/useTabs'
import config from '@/config'

export default {
	name: '编辑打印模板',
	components: {},
	data() {
		return {
			groupId: 0,
			tabList: [],
			menuList: [],
			menuProps: {
				label: (data) => {
					return data.name
				}
			},
			menuForm: {},
			cursorPosition: null,
			isTableNew: 1,
			form: {
				id: '',
				content: '',
			},
			template_name: '',
		}
	},
	mounted() {
		this.getTab()
	},
	computed: {
		// 映射 Vuex 的 state 到计算属性
		isTable() {
			return store.state.print.isTable;
		}
	},
	beforeUnmount() {
		console.log('销毁')
		tinymcePrint.remove()
	},
	watch: {
		// 监听计算属性的变化
		isTable(newValue) {
			console.log('isTable 发生变化:', newValue);
			this.isTableNew = newValue
			if (this.isTableNew != 1) {
				this.getTableChange()
			}
		}
	},
	created() {
		this.emitter.on("print_id", (msg) => {
			// A发送来的消息
			// console.log(msg)
			this.setData({id: msg})
		});
	},
	methods: {
		/**返回*/
		close() {
			useTabs.close()
      this.$router.push({ path: '/printAll/print_template' });
		},
		/**保存*/
		async submit() {
			console.log('this.form.content', this.form.content)
			var res = [];
			res = await this.$API.print.template.editTemplate.post(this.form);
			if (res.code == 1) {
				this.close()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		//表单注入数据
		async setData(data) {
			var reqData = {id: data.id}
			var res = await this.$API.print.template.detail.get(reqData);
            console.log('res :>> ', res);
			this.form.id = data.id
            this.getTab(res.data.group_id)
			this.form.content = res.data.content
			this.template_name = res.data.name
			this.handleContent()
		},
		/**获取是否表格*/
		getTable(e) {
			console.log(e, 'getTable')
		},
		changeHtml(html) {
			console.log(html,11)
			this.form.content = html
		},
		/**打印按钮点击*/
		toPrint() {
			tinymcePrint.activeEditor.execCommand('mceprint');
		},
		/**预览*/
		preview() {
			tinymcePrint.activeEditor.execCommand('mcePreview');
		},
		handleContent() {
			tinymcePrint.activeEditor.setContent(this.form.content)
			this.$nextTick(() => {
				if(this.$refs.editor && this.$refs.editor.EditorOnsize) {
					this.$refs.editor.EditorOnsize()
				}
			})
		},
		/**tab点击*/
		tabChange(e) {
			this.getMenu(this.tabList[e].data)
		},
		/**获取标签字段*/
		async getTab(e) {
			var res = await this.$API.print.formMenu.all.get({group_id:e});
			this.tabList = res.data
			if (this.tabList.length > 0) {
				this.groupId = 0
				this.getMenu(this.tabList[this.groupId].data)
			}
		},
		//加载树数据
		async getMenu(children) {
			this.menuList = children;
		},
		/**表格点击事件*/
		getTableChange() {

		},
		//树点击
		menuClick(data) {
			let realStr = '';
			if (data.form_type == 'input') {
				realStr = `<span class="qd-tiny-style" style="color: ${data.form_color}" contenteditable="false" data-qd-tag="${data.types}.${data.field}">{${data.name}}</span>`
			} else if (data.form_type == 'uploadImage') {
				realStr = `<img class="qd-tiny-img" src="${config.API_URL}/resource/image/adminapi/default/print_image_default.png" data-qd-tag="${data.types}.${data.field}" contenteditable="false">`
			} else if (data.form_type == 'table' || data.form_type == 'tableImage') {
				if (this.isTableNew == 1) {
					realStr = `<table
							style="border-collapse: collapse; width: 100%;"
							border="1"
							data-qd-table-tag="table"
							data-qd-table-value="product">
						  <tbody>
						  <tr data-qd-table-tr-tag="header"><td data-qd-table-td-tag="name" class="qd-tiny-table">${data.name}</td></tr><tr data-qd-table-tr-tag="value"><td data-qd-table-td-tag="value">`;
					if (data.form_type == 'table') {
						realStr += `<span class="qd-tiny-table" style="color: ${data.form_color}"  contenteditable="false"
							  data-qd-table-value-tag="${data.types}.${data.field}">{${data.name}}</span>`
					} else {
						realStr += `<img class="qd-tiny-img" src="${config.API_URL}/resource/image/adminapi/default/print_image_default.png" data-qd-table-value-tag="${data.types}.${data.field}" contenteditable="false">`
					}
					realStr += `</td></tr></tbody></table>`
				} else {
					$(this.isTableNew).find("[data-qd-table-tr-tag=header]").append(`<td data-qd-table-td-tag="name" class="qd-tiny-table">${data.name}</td>`);
					if (data.form_type == 'table') {
						$(this.isTableNew).find("[data-qd-table-tr-tag=value]").append(`<td data-qd-table-td-tag="value">
						  <span class="qd-tiny-table" style="color: ${data.form_color}"  contenteditable="false"
						  data-qd-table-value-tag="${data.types}.${data.field}">{${data.name}}</span></td>`);
					} else {
						$(this.isTableNew).find("[data-qd-table-tr-tag=value]").append(`<td data-qd-table-td-tag="value">
						 <img class="qd-tiny-img" src="${config.API_URL}/resource/image/adminapi/default/print_image_default.png"  contenteditable="false" data-qd-table-value-tag="${data.types}.${data.field}"></td>`);
					}
				}
			}
			var editor = tinymcePrint.activeEditor;
			// 插入内容
			editor.insertContent(realStr);
			// console.log('this.form.content', this.form.content)
			this.$refs.editor.EditorOnsize()
		},
	}
}
</script>

